package com.ls.lserp.modules.setting.web;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import groovy.util.ResourceException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.setting.entity.Category;
import com.ls.lserp.modules.setting.service.CategoryService;



/**
  * @ClassName: CategoryController
  * @Description: 物料分类
  * 
  * @author 
  * @date 2017年1月24日 下午3:12:59
  *
  */

@Controller
@RequestMapping(value = "${adminPath}/material/category")
public class CategoryController extends BaseController {
	
	// 保存 编辑 删除 方法
	@Autowired
	private CategoryService categoryService;
	
	//子项session
	private final String CATEGORYSUBLIST="categorySubList";
	/**
	  * @Title: get
	  * @Description: 获取分类信息
	  * @param @param id
	  * @param @return
	  * @return Category 
	  * @throws
	  */
	
	@ModelAttribute
	public Category get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return categoryService.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Category();
		}
	}
	
    /**
      * @Title: list
      * @Description: 查询页面
      * @param @param Category
      * @param @param request
      * @param @param response
      * @param @param model
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:category:view")
    @RequestMapping(value = {""})
    public String list(Category category, HttpServletRequest request, HttpServletResponse response, Model model) {
    	
    	// 返回页面地址
        return "modules/setting/category";
    }
    
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param category
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws ResourceException
	 */
	@RequiresPermissions("material:category:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Category category, HttpServletRequest request, HttpServletResponse response, Model model)
			throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "category");
		// 画面取得的检索项目
		String itemNameCn = category.getItemNameCn();
		// 拼接字符串供分页使用
		String searchParam = "&itemNameCn=" + itemNameCn;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<Category> page = categoryService.findList(new Page<Category>(request, response), category);
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//"+basePath + "templates//demoHtml//categoryList.txt";
		// 读取文件生成字符串
		String categoryHtml = filUtils.readFileToHtml(tempFilePath);
		String categoryName = "";
		String strHtml = "";
		int pageNo = 0;
		String strCtx = request.getContextPath()+Global.getAdminPath();
		if (!"".equals(categoryHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				categoryHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				categoryHtml = categoryHtml.replace("pageNo", "" + pageNo);
				// 分类代码
				categoryHtml = categoryHtml.replace("itemCode", StringUtils.checkStringNull(page.getList().get(i).getItemCode()));
				String categoryline = "\"popup('900px','584px','"+strCtx+"/material/category/show?id=" + page.getList().get(i).getId() + "')\"";
				// 分类id
				categoryHtml = categoryHtml.replace("itemId", categoryline);
				// 分类中文名称
				categoryHtml = categoryHtml.replace("itemNameCn", StringUtils.checkStringNull(page.getList().get(i).getItemNameCn()));
				// 分类中文名称
				categoryHtml = categoryHtml.replace("itemNameEn", StringUtils.checkStringNull(page.getList().get(i).getItemNameEn()));
				// 状态
				if ("1".equals(page.getList().get(i).getEnableFlag())) {
					categoryHtml = categoryHtml.replace("categoryBle", page.getTextMessage("common_enable"));
				} else if ("0".equals(page.getList().get(i).getEnableFlag())) {
					categoryHtml = categoryHtml.replace("categoryBle", page.getTextMessage("common_disable"));
				}
				// 描述
				categoryHtml = categoryHtml.replace("remarks", StringUtils.checkStringNull(page.getList().get(i).getRemarks()));
				// 创建人
				categoryName = page.getList().get(i).getCreateBy().getFirstName()
						+ page.getList().get(i).getCreateBy().getLastName();
				categoryHtml = categoryHtml.replace("categoryName", categoryName);
				// 创建日期
				dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date createDate = page.getList().get(i).getCreateDate();
				if (createDate!=null) {
					categoryHtml = categoryHtml.replace("createDate", dateForamat.format(createDate));
				} else {
					categoryHtml = categoryHtml.replace("createDate", "");
				}
				strHtml += categoryHtml;
			}
		}
		listMap.put("category", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	  * @Title: form
	  * @Description: 新建及编辑分类
	  * @param @param category
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("material:category:edit")
	@RequestMapping(value = "form")
	public String form(Category category,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
	    
		// 新建判断 若不为null 编辑数据
		if(category.getId()!=null){
			
	    	// 实力化子项实体类
	    	Category categorySub = new Category();
	    	
	    	// 给子项实体类赋值（关联值——项目值）
	    	categorySub.setItemValue(category.getItemValue());
	    	
	    	// 执行查询方法查询子项数据
	        List<Category> categoryList= categoryService.findSubCategory(categorySub);
	        
	        // 将子项数据list 赋值给mvc model层返回给jsp页面
	        model.addAttribute("categoryList", categoryList);
	        
	        // 将list赋值给CATEGORYSUBLIST放入缓存中
	        session.setAttribute(CATEGORYSUBLIST, categoryList);
	    }else{
	    	
	    	// 分类代码赋值（固定值MATERIAL_CATEGORY）
	    	category.setItemCode(ResourcesUtil.getConfig("categoryCD"));
	    	
	    	// 清空创建的子项
            session.setAttribute(CATEGORYSUBLIST, new ArrayList<Category>());
	    }
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("category", category);
		
		// 返回页面地址
		return "modules/setting/categoryCreate";
	}
	
	/**
	  * @Title: formSub
	  * @Description: 新建子项
	  * @param @param category
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	@RequiresPermissions("material:category:edit")
	@RequestMapping(value = "formSub")
	public String formSub(Category category,RedirectAttributes redirectAttributes, Model model,HttpSession  session) {
		
		int delIndex=category.getDelIndex();
        if(delIndex!=-1){
            // 获取当前创建的子项
            List<Category> listSubItems = (List<Category>) session.getAttribute(CATEGORYSUBLIST);
            category=listSubItems.get(delIndex);
            category.setDelIndex(delIndex);
            // 分类代码赋值（固定值MATERIAL_CATEGORY）
    		category.setItemCode(ResourcesUtil.getConfig("categoryCD"));
            
        }
		
		// 新建子项 将Category实体类赋给mvc model层 返回jsp页面
		model.addAttribute("category", category);
		
		// 返回页面地址
		return "modules/setting/categorySubCreate";
	}
	
	/**
	  * @Title: checkName
	  * @Description: 查重
	  * @param @param id
	  * @param @param itemValue
	  * @param @param itemCode
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("material:category:edit")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldItemValue,String itemValue) {
		
        try {
        	// 页面获取数据值与旧数据若相同，并且数据值不为null
            if (itemValue != null && itemValue.toUpperCase().equals(oldItemValue.toUpperCase())) {
            	// 返回true
                return "true";
            // 页面获取数据值与旧数据若不相同，查询结果为null，并且数据值不为null
            } else if (itemValue != null&& categoryService.getItemValue(itemValue) == null&&categoryService.getItemCode(itemValue)==null) {
            	// 返回true
            	return "true";
            }
            // 数据值重名
            return "false";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }
        // 数据值重名
        return "false";
	}
	
	
		/**
		 * @throws ResourceException 
		  * @Title: save
		  * @Description: 保存数据
		  * @param @param Category
		  * @param @param request
		  * @param @param model
		  * @param @param response
		  * @param @return
		  * @return String 
		  * @throws
		  */
		
		@RequiresPermissions("material:category:edit")
		@RequestMapping(value = "save")
		@ResponseBody
		public String save(Category category, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
			
			// 判断id是否为null （判断新建或修改）
			if(category.getId()!=null){
				// 编辑数据
				// 判断数据是否删除
				Category categoryNew=get(category.getId().toString());
				// 判断数据是否删除
	            if(categoryNew==null || BaseEntity.DEL_FLAG_DELETE.equals(categoryNew.getDeleteFlag())){
	                
	            	// 返回提示信息
	            	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	            }
	            
	            // 排他处理
			    if(category.getVersion()==get(category.getId().toString()).getVersion()){
			    	
			    	// 版本号加1
			    	category.setVersion(category.getVersion()+1);
			    }else{
			    	
			    	// 返回提示信息
			        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			    }
			}else{
				
				// 新建版本号赋值1
				category.setVersion(1L);
			}
				
		     // 通过缓存将子项值赋给list
			List<Category> list = (List<Category>) session.getAttribute(CATEGORYSUBLIST);
				
			// 将list赋给子项list
			category.setCategoryList(list);
	            
			// 保存分类
			categoryService.saveCategory(category);
				
			// 清空缓存,实例化
			session.setAttribute(CATEGORYSUBLIST, new ArrayList<Category>());
				
				// 保存成功返回提示信息
			return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "categorySaveSuccess")));
		}
	
    /**
      * @Title: show
      * @Description: 查看分类
      * @param @param category
      * @param @param model
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:category:view")
    @RequestMapping(value = "show")
    public String show(Category category, Model model) {
    	
    	// 实例化子项
    	Category categorySub = new Category();
    	
    	// 将项目值赋给子项实体类
    	categorySub.setItemValue(category.getItemValue());
    	
    	// 执行查询语句
        List<Category> categoryList= categoryService.findSubCategory(categorySub);
        
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("categoryList", categoryList);
        
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("category", category);
        
        // 返回页面地址
        return "modules/setting/categoryShow";
    }
    
    /**
      * @Title: delete
      * @Description: 删除
      * @param @param Category
      * @param @param response
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:category:edit")
	@RequestMapping(value = "delete")
	public String delete(Category category, HttpServletResponse response) {
		
		    try {
		    	
		    	// 执行逻辑删除方法
		    	categoryService.deleteCategory(category);
            } catch (Exception e) {
                // 记录日志
                logger.error(e.getMessage(), e);
            	// 提示错误信息
                return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
            }
		    
		    // 提示删除成功信息
			return renderString(response,AjaxDone.ok(getText("category_delete_success")));
    }
    

    /**
      * @Title: searchSubList
      * @Description: 根据父项value,查找相关子项
      * @param @param category
      * @param @param model
      * @param @param session
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:category:view")
    @RequestMapping(value = "searchSubList")
    public String searchSubList(Category category, Model model, HttpSession session) {
        try {
        	
        	// 通过缓存赋值给子项list
            List<Category> categoryList = (List<Category>) session.getAttribute(CATEGORYSUBLIST);
            
            // 将list赋值给 mvc model层返回jsp页面
            model.addAttribute("categoryList", categoryList);
            
            // 返回地址
            return "modules/setting/categoryCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        	// 发生异常 不返回
            return null;
        }
    }
    
    
    /**
      * @Title: deleteSub
      * @Description: 删除缓存子项数据
      * @param @param category
      * @param @param model
      * @param @param session
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:category:edit")
    @RequestMapping(value = "deleteSub")
    public String deleteSub(Category category, Model model,HttpSession session ) {
        try {
        	
        	// 通过缓存获取子项数据
            List<Category> categoryList = (List<Category>) session.getAttribute(CATEGORYSUBLIST);
            
            // 删除子项
            categoryList.remove(category.getDelIndex());

            // 在session里重新存入子项
            session.setAttribute(CATEGORYSUBLIST, categoryList);
            
            // 将list赋值给mvc model层返回jsp 页面
            model.addAttribute("categoryList", categoryList);
            
            // 返回地址
            return "modules/setting/categoryCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            // 返回地址
            return "modules/setting/categoryCreate";
        }
        
    }

    /**
      * @Title: saveSub
      * @Description: 保存子项数据赋值给缓存list
      * @param @param category
      * @param @param request
      * @param @param model
      * @param @param response
      * @param @param session
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:category:edit")
    @RequestMapping(value = "saveSub")
    @ResponseBody
    public String saveSub(Category category, HttpServletRequest request, Model model, HttpServletResponse response,HttpSession session){
        try {
        	
        	// 通过缓存获取list数据
            List<Category> categoryList = (List<Category>) session.getAttribute(CATEGORYSUBLIST);
        
            // 将新的实体类添加到list中
            int delIndex=category.getDelIndex();
          
            if(delIndex==-1){
            	categoryList.add(category); 
            }else{
            	categoryList.remove(delIndex);
            	categoryList.add(delIndex,category);
            }
            
            // 将list赋值给缓存session
            session.setAttribute(CATEGORYSUBLIST, categoryList);
        
            // 返回true
            return "true";
        
        }catch(Exception e){
            // 记录日志
            logger.error(e.getMessage(), e);
        	// 抛异常返回false
            return "false";
        }
        
    }
    
}
